package com.ylkj.patient.wxapi;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;

import com.examination.mlib.constants.AllStringConstants;
import com.examination.mlib.constants.ProjectConfigure;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelbiz.WXLaunchMiniProgram;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.yilijk.base.network.RequestParams;
import com.yilijk.base.network.https.HttpCallBack;
import com.yilijk.base.network.https.HttpUtils;
import com.yilijk.base.utils.ALog;
import com.ylkj.patient.MainApplication;

import org.json.JSONException;
import org.json.JSONObject;

public class WXEntryActivity extends Activity implements IWXAPIEventHandler {
    private static final String TAG = "Android_YLJK";
    private String code = null; //用户返回码
    private String getTokenUrl = null; // token url
    private String refresh_url = null; // freshtoken url
    private String request_user_url = null; // requestUserInfo url
    public static boolean changeImageAvator = false;
    private static HttpCallBack<String> callBack = null;

    public static void setCallBack(HttpCallBack<String> c) {
        callBack = c;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        WeChatUtils.api.registerApp(ConfigureConstants.WECHAT_ID);
        MainApplication.iwxapi.handleIntent(getIntent(), this);
    }

    //微信请求相应
    @Override
    public void onReq(BaseReq baseReq) {

    }
    //发送到微信请求的响应结果
    @Override
    public void onResp(BaseResp resp) {
        code = null;
        if (resp.getType() == ConstantsAPI.COMMAND_LAUNCH_WX_MINIPROGRAM){
            //唤起小程序
            WXLaunchMiniProgram.Resp launchMiniProResp = (WXLaunchMiniProgram.Resp) resp;
            String extraData =launchMiniProResp.extMsg; //对应小程序组件 <button open-type="launchApp"> 中的 app-parameter 属性
        }
        if(resp.getType()==ConstantsAPI.COMMAND_PAY_BY_WX){
            ALog.d(TAG,"onPayFinish,errCode="+resp.errCode);
        }
        switch (resp.errCode) {
            //微信授权调用成功
            case BaseResp.ErrCode.ERR_OK:
                SendAuth.Resp newResp = (SendAuth.Resp) resp;
                //获取微信传回的code
                code = newResp.code;
                if (changeImageAvator){
                    changeImageAvator = false;
                    callBack.onSuccess(code,200);
                    //获取token url
//                    RequestParams params = new RequestParams();
//                    params.put("appid", ProjectConfigure.WECHAT_ID);
//                    params.put("secret", ProjectConfigure.WECHAT_SECRET);
//                    params.put("code", code);
//                    params.put("grant_type", "authorization_code");
//                    HttpUtils.get("https://api.weixin.qq.com/sns/oauth2/access_token", params, new HttpCallBack<String>() {
//                        @Override
//                        public void onSuccess(String s, int i) {
//                            JSONObject jsonObject = null;
//                            try {
//                                jsonObject = new JSONObject(s);
//                                String access_token = jsonObject.getString("access_token");
//                                String refresh_token = jsonObject.getString("refresh_token");
//                                String openid = jsonObject.getString("openid");
//                                ALog.d(TAG, "code: " + code);
//                                ALog.d(TAG, "access_token: " + access_token);
//                                ALog.d(TAG, "refresh_token: " + refresh_token);
//                                ALog.d(TAG, "openid: " + openid);
//                                RequestParams params1 = new RequestParams();
//                                params1.put("access_token",access_token);
//                                params1.put("openid",openid);
////                                params1.put("openid","zh_CN");
//                                HttpUtils.get("https://api.weixin.qq.com/sns/userinfo", params1, callBack != null? callBack : new HttpCallBack<String>() {
//                                    @Override
//                                    public void onSuccess(String s, int i) {
//                                        ALog.e("wechatInfo 回调失败"+s);
//                                    }
//
//                                    @Override
//                                    public void onFailure(String s, int i) {
//
//                                    }
//                                });
//                            } catch (JSONException e) {
//                                e.printStackTrace();
//                            }
//                        }
//
//                        @Override
//                        public void onFailure(String s, int i) {
//
//                        }
//                    });
                }else{
                    if (resp instanceof SendAuth.Resp) {
                        ALog.d(TAG, "onResp: "+code);
                        ALog.d(TAG, "onResp: "+code);
                        Intent intent = new Intent(AllStringConstants.BroadcastReceiver);
                        intent.putExtra("wechatCode",code);         //向广播接收器传递数据
                        sendBroadcast(intent);      //发送广播
                    }
                }
                break;
            case BaseResp.ErrCode.ERR_USER_CANCEL:
                Toast.makeText(this, "取消微信授权", Toast.LENGTH_SHORT).show();
                //发送取消
                break;
            case BaseResp.ErrCode.ERR_AUTH_DENIED:
                Toast.makeText(this, "拒绝微信授权", Toast.LENGTH_SHORT).show();
                //发送被拒绝
                break;
            default:
                Toast.makeText(this, "取消微信授权", Toast.LENGTH_SHORT).show();
                //发送返回
                break;
        }
        finish();
    }

    /**
     * 请求用户token
     * @param code 请求结果返回码
     */
//    private void requestUserToken(String code) {
//        OkGo.<String>get(getTokenUrl).execute(new StringCallback() {
//            @Override
//            public void onSuccess(Response<String> response) {
//                String s = response.body();
//                JSONObject jsonObject = null;
//                try {
//                    jsonObject = new JSONObject(s);
//                    String access_token = jsonObject.getString("access_token");
//                    String refresh_token = jsonObject.getString("refresh_token");
//                    String openid = jsonObject.getString("openid");
//                    ALog.d(TAG, "run1: " + code);
//                    ALog.d(TAG, "run1: " + access_token);
//                    ALog.d(TAG, "run1: " + refresh_token);
//                    ALog.d(TAG, "run1: " + openid);
//                    //获取refresh_token
//                    refresh_url = "https://api.weixin.qq.com/sns/oauth2/refresh_token?" +
//                            "appid=" + ProjectConfigure.WECHAT_ID +
//                            "&grant_type=refresh_token" +
//                            "&refresh_token=" + refresh_token;
//                } catch (JSONException e) {
//                    e.printStackTrace();
//                }
//            }
//        });
//    }

    /**
     * OKgo请求用户refreshToken
     * @param refresh_url http url 地址
     * @param code 返回码
     */
//    private void requestUserFreshToken(String refresh_url, String code) {
//        OkGo.<String>get(refresh_url).execute(new StringCallback() {
//            @Override
//            public void onSuccess(Response<String> response) {
//                String s = response.body();
//                JSONObject jsonObject = null;
//                try {
//                    jsonObject = new JSONObject(s);
//                    String access_token = jsonObject.getString("access_token");
//                    String refresh_token = jsonObject.getString("refresh_token");
//                    String openid = jsonObject.getString("openid");
//                    String scope = jsonObject.getString("scope");
//                    ALog.d(TAG, "run2: " + code);
//                    ALog.d(TAG, "run2: " + access_token);
//                    ALog.d(TAG, "run2: " + refresh_token);
//                    ALog.d(TAG, "run2: " + openid);
//                    ALog.d(TAG, "run2: " + scope);
//                    String[] split = scope.split(",");
//                    //获取用户openID
//                    request_user_url = "https://api.weixin.qq.com/sns/userinfo?access_token="
//                            + access_token
//                            + "&openid="
//                            + openid;
//                    //OKGO请求用户信息
//                    requestUserName(request_user_url);
//                } catch (JSONException e) {
//                    e.printStackTrace();
//                }
//            }
//        });
//    }

    /**
     *OKGO请求用户信息
     * @param request_user_url http url地址
     */
//    private void requestUserName(String request_user_url) {
//        OkGo.<String>get(request_user_url).execute(new StringCallback() {
//            @Override
//            public void onSuccess(Response<String> response) {
//                ALog.d(TAG, "onSuccess: "+response.body());
//            }
//        });
//    }
}
